package com.it.schoolbookshop_back.mapper;

import com.it.schoolbookshop_back.entities.po.Category;
import org.apache.ibatis.annotations.*;

import java.util.List;
import java.util.Map;

/**
 * 分类DAO层接口
 */
@Mapper
public interface CategoryMapper {
    
    /**
     * 获取所有分类
     * @return 分类列表
     */
    @Select("SELECT * FROM categories ORDER BY id ASC")
    List<Category> findAll();
    
    /**
     * 根据ID查询分类
     * @param id 分类ID
     * @return 分类对象
     */
    @Select("SELECT * FROM categories WHERE id = #{id}")
    @Options(flushCache = Options.FlushCachePolicy.TRUE)
    Category findById(Integer id);
    
    /**
     * 根据名称查询分类
     * @param name 分类名称
     * @return 分类对象
     */
    @Select("SELECT * FROM categories WHERE name = #{name}")
    Category findByName(String name);
    
    /**
     * 添加新分类
     * @param category 分类对象
     * @return 影响行数
     */
    @Insert("INSERT INTO categories(name, description) VALUES(#{name}, #{description})")
    @Options(useGeneratedKeys = true, keyProperty = "id")
    int insert(Category category);
    
    /**
     * 更新分类信息
     * @param category 分类对象
     * @return 影响行数
     */
    @Update("UPDATE categories SET name = #{name}, description = #{description} WHERE id = #{id}")
    int update(Category category);
    
    /**
     * 删除分类
     * @param id 分类ID
     * @return 影响行数
     */
    @Delete("DELETE FROM categories WHERE id = #{id}")
    int deleteById(Integer id);
    
    /**
     * 统计分类总数
     * @return 分类总数
     */
    @Select("SELECT COUNT(*) FROM categories")
    int count();
    
    /**
     * 获取所有分类及其包含的书籍数量
     * @return 包含书籍数量的分类列表
     */
    @Select("SELECT c.*, COUNT(b.id) as bookCount " +
            "FROM categories c " +
            "LEFT JOIN books b ON c.id = b.category_id " +
            "GROUP BY c.id " +
            "ORDER BY c.id ASC")
    List<Category> findAllWithBookCount();
    
    /**
     * 统计指定分类下的书籍数量
     * @param categoryId 分类ID
     * @return 书籍数量
     */
    @Select("SELECT COUNT(*) FROM books WHERE category_id = #{categoryId}")
    int countBooksByCategory(Integer categoryId);
    
    /**
     * 获取所有分类的书籍数量
     * @return 键为分类ID，值为书籍数量的映射
     */
    @Select("SELECT category_id, COUNT(*) as count FROM books GROUP BY category_id")
    @Results({
        @Result(property = "key", column = "category_id"),
        @Result(property = "value", column = "count")
    })
    List<Map<String, Object>> getAllCategoriesBookCount();
    
    /**
     * 根据ID查询分类及其包含的书籍数量
     * @param id 分类ID
     * @return 包含书籍数量的分类对象
     */
    @Select("SELECT c.*, COUNT(b.id) as bookCount " +
            "FROM categories c " +
            "LEFT JOIN books b ON c.id = b.category_id " +
            "WHERE c.id = #{id} " +
            "GROUP BY c.id")
    @Options(flushCache = Options.FlushCachePolicy.TRUE)
    Category findByIdWithBookCount(Integer id);
} 